package com.atguigu.cart.service.impl;

import com.atguigu.cart.mapper.CartMapper;
import com.atguigu.cart.service.CartService;
import com.atguigu.clients.ProductClient;
import com.atguigu.param.CartSaveParam;
import com.atguigu.param.ProductCollectParam;
import com.atguigu.param.ProductIdParam;
import com.atguigu.pojo.Cart;
import com.atguigu.pojo.Product;
import com.atguigu.utils.R;
import com.atguigu.vo.CartVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ClassName:CartServiceInpl
 * Package:com.atguigu.cart.service.impl
 * Description:
 *
 * @Author 应永豪
 * @Create 2024/4/22 20:17
 * @Version 1.0
 */
@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    private ProductClient productClient;
    @Autowired
    private CartMapper cartMapper;

    @Override
    public R save(CartSaveParam cartSaveParam) {
//        查询商品数据
        ProductIdParam productIdParam = new ProductIdParam();
        productIdParam.setProductID(cartSaveParam.getProductId());
        Product product = productClient.productDetail(productIdParam);

        if (product == null) {
            return R.fail("商品不存在，无法添加购物车");
        }
//        检查库存

        if (product.getProductNum() == 0) {
            R ok = R.ok("没有库存，无法购买");
            ok.setCode("003");
            log.info("CartServiceImpl.save业务执行完毕,结果为：{}",ok);
            return ok;
        }

//        检查是否已经添加过
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.eq("user_id", cartSaveParam.getUserId())
                .eq("product_id", cartSaveParam.getProductId());
        Cart cart = cartMapper.selectOne(cartQueryWrapper);

        if (cart != null) {
//            说明购物车已经添加过该商品，所以只要把原有数量+1即可
            cart.setNum(cart.getNum() + 1);
            cartMapper.updateById(cart);
            R ok = R.ok("购物车存在该商品，数量+1");
            ok.setCode("002");
            log.info("CartServiceImpl.save业务执行完毕,结果为：{}",ok);
            return ok;

        }

//        添加购物车
         cart = new Cart();
        cart.setNum(1);
        cart.setUserId(cartSaveParam.getUserId());
        cart.setProductId(cartSaveParam.getProductId());
        int rows = cartMapper.insert(cart);
        log.info("CartServiceImpl.save业务执行完毕,结果为：{}",rows);
//        结果封装跟返回
        CartVo cartVo = new CartVo(product, cart);
        log.info("CartServiceImpl.save业务执行完毕,结果为：{}",cartVo);
        return R.ok("购物车数据添加成功",cartVo);
    }

    @Override
    public R list(Integer userId) {
//        根据用户id查询购物车数据
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.eq("user_id",userId);
        List<Cart> carts = cartMapper.selectList(cartQueryWrapper);

//        判断是否存在，如果不存在就返回一个空集合防止前端报错

        if (carts==null || carts.size()==0){
            carts= new ArrayList<>();
            return R.ok("购物车空空如也",carts);
        }

//        如果存在购物车商品

        ArrayList<Integer> productIds = new ArrayList<>();
        for(Cart cart: carts){
            productIds.add(cart.getProductId());
        }
        ProductCollectParam productCollectParam = new ProductCollectParam();
        productCollectParam.setProductIds(productIds);
        List<Product> productList = productClient.cartList(productCollectParam);

//        将商品集合转换成map，key为商品id,value为商品
        Map<Integer,Product> productMap =productList.stream().collect(Collectors.toMap(Product::getProductId, v->v));

        ArrayList<CartVo> cartVos = new ArrayList<>();
        for(Cart cart:carts){
            CartVo cartVo = new CartVo(productMap.get(cart.getProductId()), cart);
            cartVos.add(cartVo);
        }
        R ok = R.ok("数据库数据查询成功", cartVos);
        log.info("CartServiceImpl.list业务执行完毕,结果为：{}",cartVos);
        return ok;
    }

    @Override
    public R update(Cart cart) {
        ProductIdParam productIdParam = new ProductIdParam();
        productIdParam.setProductID(cart.getProductId());
        Product product = productClient.productDetail(productIdParam);

//        判断库存
        if (cart.getNum() > product.getProductNum()){
            log.info("CartServiceImpl.update业务执行完毕,结果为：{}","修改失败，库存不足");
            return R.fail("修改失败，库存不足");
        }

//        修改数据库
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.eq("user_id",cart.getUserId()).eq("product_id",cart.getProductId());
        Cart newCart = cartMapper.selectOne(cartQueryWrapper);

        newCart.setNum(cart.getNum());
        int rows = cartMapper.updateById(newCart);
        log.info("CartServiceImpl.update业务执行完毕,结果为：{}",rows);


        return R.ok("修改购物车数量成功");


    }

    @Override
    public R remove(Cart cart) {
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.eq("user_id",cart.getUserId()).eq("product_id",cart.getProductId());
        Cart newCart = cartMapper.selectOne(cartQueryWrapper);

        int rows = cartMapper.delete(cartQueryWrapper);

        log.info("CartServiceImpl.remove业务执行完毕,结果为：{}",rows);


        return R.ok("删除购物车数据成功");
    }

    @Override
    public void clearIds(List<Integer> cartIds) {
        cartMapper.deleteBatchIds(cartIds);
        log.info("CartServiceImpl.remove业务执行完毕,结果为：{}",cartIds);
    }
}
